package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author LA
 * @Date 2024/8/16 15:02
 * @Description: 全局id生成器
 */
@Component
public class RedisIdWorker {
    //开始时间戳
    private static final long BEGIN_TIMESTART = 1704067200;  //根据下方main方法获取初始时间
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public long nextId(String keyPrefix){
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - BEGIN_TIMESTART;
        //2.生成序列号
            //获取当前日期，精确到天
        String format = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增长
        Long count = stringRedisTemplate.opsForValue().increment("increment:" + keyPrefix + ":" + format); //返回值代表这个键的值执行完递增操作后的新值
        //3.拼接并返回
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(Long.toBinaryString(timeStamp)); //long型转为二进制并拼接
        stringBuilder.append(Long.toBinaryString(count));
        long l = Long.parseLong(stringBuilder.toString(),2); //二进制转为long型
        return l;
    }

    public static void main(String[] args) {
        //生成初始时间
        LocalDateTime time = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
        //转换成秒数
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }


}
